﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WMS.HelperClasses;
using WHMS.EntityClasses;
using WHMS.HelperClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;
using WHMS.FactoryClasses;

namespace WMS
{
	public partial class ProductsForm : Form
	{
		public ProductsForm()
		{
			InitializeComponent();

			DALHelper.GetTypedView(lookUpTypes, null, new SortExpression(LookupFields.Order | SortOperator.Ascending));

			var types = new DataView(lookUpTypes);
			types.RowFilter = "type = 'T'";
			TypesDS.DataSource = types;

			var units = new DataView(lookUpTypes);
			units.RowFilter = "type = 'U'";
			UnitDS.DataSource = units;

			var unitTypes = new DataView(lookUpTypes);
			unitTypes.RowFilter = "type = 'UT'";
			UnitTypeDS.DataSource = unitTypes;

			//UnitDS.Filter = "type = 'U'";
			//UnitTypeDS.Filter = "type = 'UT'";
			//_itemTypes.EntityFactoryToUse = new ItemTypeEntityFactory();
			//Business.GetLookup(_itemTypes, ItemTypeFields.Id, ItemTypeFields.Order, ItemTypeFields.Name);
			//DALHelper.FetchCollection(_itemTypes, null, null, new SortExpression(ItemTypeFields.Order | SortOperator.Ascending) ); //new RelationPredicateBucket(SystemLookupFields.Type == "ItemType"), null, sorter);
			//DALHelper.FetchCollection(_itemUnits, null, null, new SortExpression(UnitFields.Order | SortOperator.Ascending));//new RelationPredicateBucket(SystemLookupFields.Type == "ItemUnit"), null, sorter);
			//DALHelper.FetchCollection(_unitTypes, null, null, new SortExpression(UnitTypeFields.Order | SortOperator.Ascending)); //new RelationPredicateBucket(SystemLookupFields.Type == "UnitType"), null, sorter);

			var dataForm = new DataMngrFormBase<ItemEntity>(_items, dataGridView1, bindingSource1, SaveBtn, SaveResult, DeleteResult,null,null,true,NextPageBtn,PrevPageBtn);
			dataForm.SetMNInfo(typeof(ItemSupplierEntity), AllList, AssignedList, SupplierFields.Id, SupplierFields.Name, ItemSupplierFields.SupplierId, ItemSupplierFields.ItemId);
			dataForm.SetMNAssociationButtons(AssignSelectedBtn, AssignAllBtn, UnAssignSelectedBtn, UnAssignAllBtn, SaveDetailsBtn);
			dataForm.SetNumericFields(new List<int> { 6});
			dataForm.SetMandatoryFields(new List<int> { 0, 1 });
			dataForm.MNSaved += new DataMngrFormBase<ItemEntity>.RaiseMNSaved(dataForm_MNSaved);

			var uniqueFields = new Dictionary<int, EntityField2>();
			uniqueFields.Add(0, ItemFields.Code);
			uniqueFields.Add(1, ItemFields.Name);
			dataForm.SetUniqueFields(uniqueFields, ItemFields.Id);
		}

		void dataForm_MNSaved(int selectedId)
		{
			MessageBox.Show("تم الحفظ بنجاح.");
		}

        

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //I would like here to remove duplicated items if I need to add item with the same code twice 
            if (e.ColumnIndex == codeDataGridViewTextBoxColumn.Index)
            {
                var dt = Business.GetItemDetails(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
                if (dt.Rows.Count <= 0)
                    return;

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    if (dataGridView1.Rows[i].Cells[idDataGridViewTextBoxColumn.Index].Value != null &&
                        (int)dataGridView1.Rows[i].Cells[idDataGridViewTextBoxColumn.Index].Value == (int)dt.Rows[0][0])
                    {
                        MessageBox.Show("تم اضافة هذا الصنف من قبل", "خطأ", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        dataGridView1.Rows.RemoveAt(e.RowIndex);
                        return;
                    }
                }

             
            }
        }

        private void SearchBtn_Click(object sender, EventArgs e)
        {
            //Open the search form for products using code or name 
            var itemPickerForm = new ItemPickerForm(1);
            if (itemPickerForm.ShowDialog() == DialogResult.OK)
            {
                GetItemDetailsByItemId(itemPickerForm.SelectedItemId);
            }
        }

        private void GetItemDetailsByItemId(int itemId)
        {
            //var collection = new EntityCollection<ItemEntity>();

            var filter = new RelationPredicateBucket(ItemFields.Id == itemId);


            _items.Clear();

            DALHelper.FetchCollection(_items, filter);

            if (_items.Count <= 0)
            {
                //InitializeDataSources();
                return;
            }

            //Fill ItemName & ItemCode columns in retrieving order 
            if (dataGridView1.Rows.Count > 0)
            {
                for (int currentRow = 0; currentRow < dataGridView1.Rows.Count - 1; currentRow++)
                {
                    int productItemId = Int32.Parse(dataGridView1.Rows[currentRow].Cells[idDataGridViewTextBoxColumn.Index].Value.ToString());
                    GetItemDetailsByItemId(currentRow, productItemId);
                }

            }
          
            return;
        }

        private void GetItemDetailsByItemId(int rowIndex, int itemId)
        {
            DataTable itemDT = Business.GetItemDetails(itemId);
            if (itemDT.Rows.Count <= 0)
                return;

            dataGridView1.Rows[rowIndex].Cells[codeDataGridViewTextBoxColumn.Index].Value = itemDT.Rows[0][0].ToString();
            dataGridView1.Rows[rowIndex].Cells[nameDataGridViewTextBoxColumn.Index].Value = itemDT.Rows[0][1].ToString();
            dataGridView1.Rows[rowIndex].Cells[idDataGridViewTextBoxColumn.Index].Value = itemId;

            return;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Open the search form for products using name 
            var itemPickerForm = new ItemPickerForm(1);
            if (itemPickerForm.ShowDialog() == DialogResult.OK)
            {
                GetItemDetailsByItemId(itemPickerForm.SelectedItemId);
            }

        }

        private void btnSearchProduct_Click(object sender, EventArgs e)
        {
            string name;
            var searchForm = new fromGeneralEntityPicker("Item");
            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                name = searchForm.Name;
                RelationPredicateBucket filter2 = new RelationPredicateBucket(ItemFields.Code == searchForm.SelectedItemCode);
                _items.Clear();
                DALHelper.FetchCollection(_items, filter2);

            }
        }

      
	}
}
